import {
  Controller,
  Post,
  Get,
  Patch,
  Delete,
  Param,
  Body,
  ParseIntPipe,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import { ObjectType, CommonResponse } from 'src/types';
import { responseWrapper } from 'src/utils';

@Controller('posts')
export class PostsController {
  constructor(private readonly postService: PostsService) {}

  @Post()
  async create(@Body() data: ObjectType): Promise<CommonResponse> {
    try {
      const res = await this.postService.create(data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  async deleteById(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      return await this.postService.deleteById(id);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Patch(':id')
  async modifyById(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: ObjectType,
  ): Promise<CommonResponse> {
    try {
      const res = await this.postService.modifyById(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get()
  async list(): Promise<CommonResponse> {
    try {
      const res = await this.postService.list();
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getById(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.postService.getById(id);
      return responseWrapper(res || { message: '没找到' }, !res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
